import { query as queryUsers, queryCurrent } from '@/services/user'

const UserModel = {
  namespace: 'user',
  state: {
    currentUser: {},
  },
  effects: {
    * fetch (_, { call, put }) {
      const response = yield call(queryUsers)
      yield put({
        type: 'save',
        payload: response,
      })
    },

    //获取当前的用户信息
    * fetchCurrent (_, { call, put }) {
      //先从本地取  没有再请求
      const adminInfo = localStorage.getItem('adminInfo')
      let response = {}
      if (!adminInfo) {
        response = yield call(queryCurrent)
        if (response.id !== undefined) {
          //将获取到的用户信息 放在localStorage(这里面只能放字符串)中
          localStorage.setItem('adminInfo', JSON.stringify(response))
        }
      } else {
        response = JSON.parse(adminInfo)
      }
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      })
    },
  },
  reducers: {
    saveCurrentUser (state, action) {
      return { ...state, currentUser: action.payload || {} }
    },

    changeNotifyCount (
      state = {
        currentUser: {},
      },
      action,
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      }
    },
  },
}
export default UserModel
